package com.wpf.servlet;

import com.wpf.bean.Userbean;
import com.wpf.dao.UserDAO;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class EditData extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public EditData() {}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Userbean olduserbean = new Userbean();
		olduserbean = (Userbean) session.getAttribute("edituser");
		String userName = olduserbean.getUsername();
		String loginName = (String) session.getAttribute("username");
		UserDAO userdao = new UserDAO();
		Userbean edituserbean = new Userbean();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String ID = request.getParameter("id");
		String UserName = request.getParameter("newusername");
		String PassWord = request.getParameter("newpassword");
		String ComPass = request.getParameter("compass");
		String Email = request.getParameter("newemail");
		String Birthday = request.getParameter("newbirthday");
		if(ID==""||ID==null) {
			request.setAttribute("EditMessage", "<font size='1' color='red'>编辑错误！</font>");
			request.getRequestDispatcher("/wpf_updata.jsp").forward(request, response);
		}else if(!PassWord.equals(ComPass)){
			request.setAttribute("EditMessage", "<font size='1' color='red'>两次密码不一致！</font>");
			request.getRequestDispatcher("/wpf_updata.jsp").forward(request, response);
		}else {
			edituserbean.setId(Integer.parseInt(ID));
			edituserbean.setUsername(UserName);
			edituserbean.setPassword(PassWord);
			edituserbean.setEmail(Email);
			try {edituserbean.setBirthday(sdf.parse(Birthday));} catch (ParseException e) {};
			if(userdao.update(edituserbean)) {//修改成功
				if(loginName.equals(userName)) {//编辑当前登录者信息后需要重新登录
					request.getRequestDispatcher("/wpf_LoginOutServlet").forward(request, response);
				}else {
					session.setAttribute("operationtip","<font size='2' color='orange'>编辑成功！</font>");
					request.getRequestDispatcher("/wpf_RefreshData").forward(request, response);
				}
			}else {
				request.setAttribute("EditMessage", "<font size='1' color='red'>编辑失败！</font>");
				request.getRequestDispatcher("/wpf_updata.jsp").forward(request, response);
			}
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
